package com.qf.servlet;



import com.qf.entity.BooksBorrow;
import com.qf.service.ReturnService;
import com.qf.service.impl.ReturnServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

@WebServlet(urlPatterns = "/returnServlet")
public class ReturnServlet extends BaseServlet{
    ReturnService returnService;
    @Override
    public void init() throws ServletException {
        returnService=new ReturnServiceImpl();
    }


    public void selectBorrowBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        returnService.selectBorrowBook();
    }

    public void giveBackBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException {
        PrintWriter out = response.getWriter();
//        Object user = request.getSession().getAttribute("user");
//        if(user==null){
//            out.write("未登录，请登录");
//            return;
//        }
        //解析日期时间参数
        int id = Integer.parseInt(request.getParameter("id"));
//        String name=((User)request.getSession().getAttribute("user")).getName();
        String name=request.getParameter("name");
        BooksBorrow booksBorrow = returnService.selectBorrowBookByIdAndName(id, name);
        if(booksBorrow==null){
            out.write("查询失败");
            return;
        }else {
            LocalDateTime return_dateTime = LocalDateTime.now();

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String return_date = return_dateTime.format(formatter);

            // 执行归还图书的逻辑处理并更新数据库借阅表状态
            // 修改用户借阅记录等
            int num = returnService.giveBackBook(id, name, return_date, null);
            // 返回归还结果给客户端
            if (num > 0) {
                //计算逾期天数
                long late = ChronoUnit.DAYS.between(booksBorrow.getEnd_date(), return_dateTime);
                boolean isillegal = true;
                if (late > 0) isillegal = false;
                if (isillegal == true) {
                    out.write("图书按时归还成功");
                } else {
                    out.write("图书归还成功，逾期" + late + "天");
                }
            } else {
                out.write("图书归还失败");
            }
        }

        out.close();
    }
}
